package com.xhy.documents_collection.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.annotations.OperLog;
import com.xhy.documents_collection.entity.PO.Notice;
import com.xhy.documents_collection.entity.PO.User;
import com.xhy.documents_collection.enums.BusinessType;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.service.SysNoticeService;
import com.xhy.documents_collection.service.UserService;
import com.xhy.documents_collection.thread_pool.LogThreadPool;
import com.xhy.documents_collection.utils.R;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: Xhy
 * CreateTime: 2023-03-20 10:21
 * 通知
 */
@RequestMapping("/admin/notice")
@RestController
public class ANoticeController {

    @Resource
    SysNoticeService noticeService;

    @GetMapping("/page")
    @Authority("admin:notice:page")
    public R list(@RequestParam(value = "page") Long current,
                  @RequestParam(value = "limit") Long limit,
                  @RequestParam(required = false) String title) {

        Page<Notice> page = noticeService.page(new Page<>(current, limit),
                new LambdaQueryWrapper<Notice>()
                        .like(!ObjectUtils.isEmpty(title), Notice::getTitle, title)
        .orderByDesc(Notice::getGmtCreated));

        return R.ok().data("data",page.getRecords()).count(page.getTotal());
    }


    @PostMapping
    @Authority("admin:notice:add")
    @OperLog(title = ServiceType.NOTICE,businessType = BusinessType.INSERT)
    public R add(@RequestBody @Validated Notice notice){
        notice.setUserId(UserHolder.get());
        noticeService.save(notice);
        // 通知所有用户
        LogThreadPool.helpMe();
        return R.ok().message("发布成功");
    }

    @PutMapping
    @Authority("admin:notice:update")
    @OperLog(title = ServiceType.NOTICE,businessType = BusinessType.UPDATE)
    public R update(@RequestBody @Validated Notice notice){
        noticeService.updateById(notice);
        return R.ok().message("修改成功");
    }

    @DeleteMapping("/{ids}")
    @Authority("admin:notice:delete")

    @OperLog(title = ServiceType.NOTICE,businessType = BusinessType.DELETE)
    public R delete(@PathVariable String ids){
        List<Integer> idList = Arrays.asList(ids.split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
        noticeService.removeByIds(idList);
        return R.ok().message("删除成功");
    }
}
